package fede.common.utils;

import java.util.Calendar;

public class MyTimer {
	
	private Long start = null;
	private Long end = null;
	
	
	public MyTimer() {}
	
	
	public void start() {
		Calendar cal = Calendar.getInstance();
		setStart(cal.getTimeInMillis());
	}
	
	public void stop() {
		Calendar cal = Calendar.getInstance();
		setEnd(cal.getTimeInMillis());
	}
	
	/**
	 * @return null se start o end sono = null, altrimenti la durata registrata
	 */
	public Long getDurationInMillis() {
		if(getStart()==null || getEnd()==null)		return null;
		
		return (getEnd() - getStart());
	}
	
	public String getDurationAsString() {
		if(getStart()==null || getEnd()==null)		return null;
		
		String s = "";
		
		long durata = getDurationInMillis();
		if(durata < 1000) {
			s = "0.";
			s += (new String(durata+"").length()==1 ? "00" : "");
			s += (new String(durata+"").length()==2 ? "0" : "");
			s += durata + " sec";
			return s;
		}
		int mil = (int) (durata % 1000);
		long tmp = (int) Math.floor((double) durata / 1000);
		
		if(tmp < 60)		return tmp + "." + mil + " sec";
		int sec = (int) (tmp % 60);
		tmp = (int) Math.floor((double) tmp / 60);
		
		if(tmp < 60)		return tmp + " min, " + sec + "." + mil + " sec";
		int min = (int) (tmp % 60);
		tmp = (int) Math.floor((double) tmp / 60);
		
		if(tmp < 24)		return tmp + (tmp>1 ? " ora, " : " ore, ") + min + " min, " + sec + "." + mil + " sec";
		int ore = (int) (tmp % 24);
		tmp = (int) Math.floor((double) tmp / 24);
		
		return tmp + " gg, " + ore + (ore>1 ? " ora, " : " ore, ") + min + " min, " + sec + "." + mil + " sec";
	}




	private Long getStart() {
		return start;
	}
	private Long getEnd() {
		return end;
	}
	private void setStart(Long start) {
		this.start = start;
	}
	private void setEnd(Long end) {
		this.end = end;
	}
	
}
